import router from '../../router'
import request from '../../utils/request'
import { User, Token } from '../../utils/storage'

const user = {
  state: {
    userInfo: User.get(),
    menuList: [],
    permissionList: [] // 权限列表
  },
  getters: {
    userInfo: state => state.userInfo,
    menuList: state => state.menuList,
    permissionList: state => state.permissionList // 权限
  },
  mutations: {
    setUserInfo(state, userInfo) {
      User.set(userInfo)
      state.userInfo = userInfo
    },
    setMenuList(state, list) {
      state.menuList = list
    },
    setPermissionList(state, list) {
      state.permissionList = list
    }
  },
  actions: {
    logout({ commit }, noRedirect) {
      request.get('/api/SysUser/logout')
      commit('setUserInfo', null)
      // 删除Cookie
      Token.remove()
      if (noRedirect) {
        router.replace('/login')
        setTimeout(() => {
          // 重新实例化VUE路由器对象以避免bug
          window.location.reload()
        }, 80)
      } else {
        // 重新实例化VUE路由器对象以避免bug
        window.location.reload()
      }
    },
    addUserMenus({ commit }, menus) {
      // TODO 动态添加菜单
      commit('setMenuList', menus)
    }
  }
}

export default user
